#!/usr/bin/env python

import sys
import component
import resource.string.app as r

from twisted.internet.serialport import SerialPort

from .._console import Console

class Server(Console):

    def run(self):
        self.greeting(r)
        self.info('Press Ctrl+C to stop.\n\n')
        
        port = self._args.port
        self.verbose('Serial Port: %s' % port)
        
        baudrate = self._args.baudrate
        self.verbose('Serial Port Baudrate: %s\n' % baudrate)
        
        proxyInfo = None
        if self._args.proxyType:
            import httplib2
            proxyInfo = httplib2.ProxyInfo(self._args.proxyType,
                                           self._args.proxyHost,
                                           self._args.proxyPort,
                                           None,
                                           self._args.proxyUsername,
                                           self._args.proxyPassword)
        
        if sys.platform == 'win32':
            from twisted.internet import win32eventreactor
            win32eventreactor.install()
        
        # This must be called after win32eventreactor.install()
        from twisted.internet import reactor
        
        protocol = component.Protocol()
        protocol.console = self
        protocol.proxyInfo = proxyInfo
        serialPort = SerialPort(protocol, port, reactor, baudrate=baudrate)
        reactor.run()
        
        self.farewell()
        